<template>
  <zsearch v-loading="loading">
      <template #date>
      </template>
      <template #select>
        
      </template>
      <template #btns>
        <!-- <el-button class="btn-1" @click="hanledSearch" v-jurisdiction="'pay:order:discount:setting:list'">查询</el-button> -->
			  <el-button class="btn-2" @click="openCoupon" v-jurisdiction="'pay:order:discount:setting:add'">添加订单优惠</el-button>
      </template>
      <template #table>
        <ztable 
          :tableData='data' 
          :strucs='groupData'
          :header-cell-style="{background:'#11b9d0', color:'#fff'}"
          :height="'100%'"
          :isshowOperation="true"
        >
        <template #default="slotData">
          <el-button v-if="slotData.rowData.status === '关闭'" @click="handleClick(slotData.rowData, 'open')" 
            type="text" 
            size="small" 
            class="operation" 
            v-jurisdiction="'pay:order:discount:setting:updateStatus'"
            >开启</el-button>
          <el-button v-if="slotData.rowData.status === '开启'" @click="handleClick(slotData.rowData, 'close')" 
            type="text" 
            size="small" 
            class="operation"
            v-jurisdiction="'pay:order:discount:setting:updateStatus'"
            >关闭</el-button>
          <el-button @click="handleClick(slotData.rowData, 'edit')" type="text" size="small" class="operation" v-jurisdiction="'pay:order:discount:setting:update'" >修改</el-button>
          <el-button @click="handleClick(slotData.rowData, 'del')" type="text" size="small" class="operation" v-jurisdiction="'pay:order:discount:setting:del'">删除</el-button>
        </template>
        </ztable>
      </template>
      <template #page>
        <zpage
            :currentPage="current" 
            :total="total" 
            @handleSizeChange="handleSizeChange" 
            @handleCurrentChange="handleCurrentChange"
        ></zpage>
      </template>
    </zsearch>

    <zdialog :title="titleDialod" @handleClose="closeDialog" v-model="dialogVisible" :btnData="dialogBtnData">
      <template #body>
        <div class="flex-wrap">
          <div class="leftToRight-layout">
            <div class="label">
              <span>标题</span>
            </div>
            <div class="operations">
              <el-input v-model="title"></el-input>
            </div>
          </div>
          <div  class="leftToRight-layout">
            <div class="label">
              <span>时间</span>
            </div>
            <div class="operations">
              <el-date-picker
                v-model="Time"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              >
              </el-date-picker>
            </div>
          </div>

          <div class="leftToRight-layout">
            <div class="label">
              <span>排序</span>
            </div>
            <div class="operations">
              <el-input-number
                  style="width: 100%;"
                  v-model="orderNum"
                  :min="1"
                  :max="100"
                ></el-input-number>
            </div>
          </div>
          <div class="leftToRight-layout">
            <div class="label">
              <span>类型</span>
            </div>
            <div class="operations">
              <el-select v-model="type" @change="selectType"  placeholder="请选择">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>

          <component :is="showWidget(item.type)" v-for="item in ruleTypeDataList" :key="item.name" :struc="item" :passWidth="50" />
        </div>
			</template>
    </zdialog>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref, watch, computed } from '@vue/runtime-core'

import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdialog from '@components/dialog/dialog.vue'

import useConfgin from './../../../hook/getconfig'
import useShowWidget from "./../../../components/widget/usechoose";
import useRequet, { RespData } from "./../../../hook/network"
import { ElMessage, ElMessageBox } from 'element-plus'

type Options = {
  id: string | number,
  name: string | number
}

const configID = 547
export default defineComponent({
  name: 'OrderDiscount',
  components: {
    ztable,
    zpage,
    zsearch,
    zdialog
  },
  setup() {
    const showWidget = useShowWidget;
    const rowList = useConfgin(configID)
    console.log('订单优惠', rowList)
    const groupData = rowList.groupDataList.value;
    const request = useRequet({ path: "" });
    let search = reactive({
      name: '',

      loading: false,

      current: 1,
      size: 10,
      total: 0,

      timeTypeOptions:[] as Options[],
      Time: [] as string[],
      typeOptions: [] as Options[],
      ruleTypeOptions: [] as Options[],
      isClick: false,
    })
    let addCoupon = reactive({
      id: '',
      title: '',
      orderNum: 1,
      startTime: '',
      endTime: '',
      startTimeDay: '',
      endTimeDay: '',
      type: '',
      other: {} as any,
      
    })
    const data = ref([])
    const ruleTypeDataList =  ref([] as DataSource[])
    const titleDialod = ref('')
    
    //搜索
    const hanledSearch = () => {
      req()
    }
    // 分页
    const handleCurrentChange = (val: number) => {
			search.current = val
      req()
		}
    const handleSizeChange = (val: number) => {
      search.size = val
      req()
		}

    
    // 得到列表
    const req = () => {
      search.loading = true
      request.sendRequest({
        address: 'pay/order_discount/getOrderDiscountRulePage',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
					data.value = resp.data.records

          search.total = resp.data.total
          search.current = resp.data.current

          search.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
      search.loading = false
    }
    req()
    // 得到类型
    const getItemTypeSelect = () => {
      request.sendRequest({
        address: 'pay/order_discount/getOrderTypeSelect',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          search.typeOptions = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }
    getItemTypeSelect()

    // 得到逻辑类型的数据
    const getRuleTypeData = (type: string) => {
      return new Promise((resolve, reject) => {
        request.sendRequest({
          address: 'pay/order_discount/getOrderTypeOption',
          params: {
            ruleType: type
          },
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            ruleTypeDataList.value = resp.data
            resolve(resp)
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            reject()
          },
          method: "POST",
        })
      })
      
    }

    const selectType = (val: string) => {
      if(val) {
        getRuleTypeData(val)
      }
      
    }

    // 选中类型的 定义类型
    interface DataSource {
      dataSource: string,
      must: number,
      name: string,
      type: number,
      value: string,
      viewName: string
    }

    const handleClick = (data: any, type: string) => {
      let id = data.id
      if(type === 'open') {
        openItem(id)
      }
      if(type === 'close') {
        closeItem(id)
      }
      if(type === 'del') {
        deletedItem(id)
      }
      if(type === 'edit') {
        editItem(data, id)
      }
    }
    // 开启
    const openItem = (id: number) => {
      request.sendRequest({
        address: `pay/order_discount/openOrderDiscountRule/${id}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          ElMessage.success('开启' + resp.msg)
          req()
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
    }
    // 关闭
    const closeItem = (id: number) => {
      request.sendRequest({
        address: `pay/order_discount/closeOrderDiscountRule/${id}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          ElMessage.success('关闭' + resp.msg)
          req()
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
    }

    const editItem = async(data: any, id: number) => {
      ruleTypeDataList.value = []
          addCoupon.type = data.type
          await getRuleTypeData(data.type)
          
          addCoupon.id = data.id
          addCoupon.title = data.title
          addCoupon.orderNum = data.orderNum
          search.Time[0] = data.startTime
          search.Time[1] = data.endTime
          
          titleDialod.value = '修改项目优惠'

          let other = JSON.parse(data.other)

          ruleTypeDataList.value.forEach((i: DataSource) => {
            for(let o in other) {
              if(i.name === o) {
                i.value = other[o]
              }
            }
          })

          dialogVisible.value = true
          
    }
    // 删除
    const deletedItem = (id: number) => {
      ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            request.sendRequest({
              address: `pay/order_discount/delOrderDiscountRule/${id}`,
              params: {},
              success: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(resp.msg)
                ElMessage.success('删除' + resp.msg)
                req()
              },
              fail: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(resp.msg)
                
              },
              method: "POST",
            })
            }).catch(() => {
            ElMessage({
              type: 'info',
              message: '已取消删除',
            });
          })
    }

    const closeDialog = () => {
      dialogVisible.value = false
      reset()
    }
    const reset = () => {
      addCoupon.id = ''
      addCoupon.title = ''
      addCoupon.other = {}
      addCoupon.startTime = ''
      addCoupon.endTime = ''
      addCoupon.startTimeDay = ''
      addCoupon.endTimeDay = ''
      addCoupon.type = ''
      search.Time = []
      
    }

    const dialogVisible = ref(false)

    const openCoupon = () => {
      ruleTypeDataList.value = []
      titleDialod.value = '添加订单优惠'
      reset()
      dialogVisible.value = true
    }

    const dialogBtnData = [
      {
        name: '取消',
				func: (data:object) => {
					console.debug('取消',JSON.parse(JSON.stringify(data)))
          dialogVisible.value = false
          reset()
				}
      },
      {
        name: '保存',
        func: (data:object) => {
					console.debug('保存',JSON.parse(JSON.stringify(data)))
          if(search.Time.length > 0) {
            addCoupon.startTime = search.Time[0]
            addCoupon.endTime = search.Time[1]
          }
          ruleTypeDataList.value.forEach( (item: DataSource) => {
            addCoupon.other[item.name] = item.value
          })
          
          if(!addCoupon.title) {
            ElMessage.warning('请输入标题')
            return
          }
          if(!addCoupon.type) {
            ElMessage.warning('请选择类型')
            return
          }
          if(search.Time.length < 0) {
            ElMessage.warning('请选择时间')
            return
          }

          if(!search.isClick) {

            if(addCoupon.id) {
              request.sendRequest({
                address: 'pay/order_discount/updateOrderDiscountRule',
                params: addCoupon,
                success: (resp: RespData) => {
                  if(resp.code !== 0) return ElMessage.error('修改'+ resp.msg)
                  ElMessage.success('修改'+ resp.msg)
                  closeDialog()
                  req()
                  
                },
                fail: (resp: RespData) => {
                  if(resp.code !== 0) return ElMessage.error('添加'+ resp.msg)
                  
                },
                method: "POST",
              })
            } else {
              request.sendRequest({
                address: 'pay/order_discount/addOrderDiscountRule',
                params: addCoupon,
                success: (resp: RespData) => {
                  if(resp.code !== 0) return ElMessage.error('添加'+ resp.msg)
                  ElMessage.success('添加'+ resp.msg)
                  closeDialog()
                  req()
                  
                },
                fail: (resp: RespData) => {
                  if(resp.code !== 0) return ElMessage.error('添加'+ resp.msg)
                  
                },
                method: "POST",
              })
            }
            
          }
          
				}
      }
    ]

    
    return { 
      data, 
      groupData,
      titleDialod,
      ...toRefs(search),
      hanledSearch,
      handleCurrentChange,
      handleSizeChange,
      ...toRefs(addCoupon),
      handleClick,
      selectType,


      request,

      ruleTypeDataList,
      dialogVisible,
      openCoupon,
      closeDialog,
      dialogBtnData,
      showWidget,
    }
  }
})
</script>

<style lang="scss" scoped>
.f-d {
  display: flex;
  align-items: center;
  .input-1 {
    padding-right: 10px;
  }
}

.leftToRight-layout {
  width: 50%;

  .operations {
    margin-right: 8px;
  }
}


.f-a {
  display: flex;
  align-items: center
}
</style>